/*
 * BinaryStream.cpp
 *
 *  Created on: Jan 13, 2014
 *      Author: knuke
 */

#include "BinaryStream.h"
#include <fstream>

using std::ofstream;
using std::ios;

namespace graphiclicious_converter
{

  BinaryStream::BinaryStream() : buffered_(true)
  {

  }

  BinaryStream::~BinaryStream()
  {
    if (out_.is_open())
      out_.close();
  }

  void BinaryStream::open(std::string filename, bool buffered)
  {
    out_.open(filename.c_str(), ios::binary | ios::out);
    buffered_ = buffered;
  }

  void BinaryStream::writeInt(int i)
  {
    void* int_ptr_void = static_cast<void*> (&i);
    uchar* int_ptr_uchar = static_cast<uchar*> (int_ptr_void);
    writeBytesReverse(int_ptr_uchar, sizeof(i));
  }

  void BinaryStream::writeFloat(float f)
  {
    void* float_ptr_void = static_cast<void*>(&f);
    uchar* float_ptr_uchar = static_cast<uchar*>(float_ptr_void);
    writeBytesReverse(float_ptr_uchar, sizeof(f));
  }

  void BinaryStream::writeBytes(uchar* bytes, int len)
  {
    out_.write(reinterpret_cast<char*> (bytes), len);
    if (!buffered_) out_.flush();
  }

  void BinaryStream::writeBytesReverse(uchar* bytes, int len)
  {
    for (int byte_idx = len - 1; byte_idx >= 0; byte_idx--)
      out_.write(reinterpret_cast<char*> (&bytes[byte_idx]), 1);
    if (!buffered_) out_.flush();
  }

  void BinaryStream::writeFloats(float* f, int len)
  {
    COUNTER_LOOP(idx, 0, len)
      writeFloat(f[idx]);
  }

  void BinaryStream::flush()
  {
    out_.flush();
  }

} /* namespace graphiclicious_converter */
